//
//  YCEditDailyRecodeViewController.m
//  YCSchool
//
//  Created by gmall on 16/5/12.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  发表日志

#import "YCEditDailyRecodeViewController.h"
#import "YCPlaceholderTextView.h"
#import "YCImageCollectionViewCell.h"
#import "PreviewPhotoViewController.h"
#import "MultipleImagePickerViewController.h"


#pragma mark -

@interface YCEditDailyRecodeViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UITableView *tableView;
/** textView  */
@property (nonatomic, strong) YCPlaceholderTextView *textView;
@property (nonatomic, strong) UIToolbar *inputAccessoryView;
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *photoMutableArray;
@property (nonatomic, assign) NSUInteger numPhoto;
@end

@implementation YCEditDailyRecodeViewController

- (UIView *)headerView
{
    if (!_headerView)
    {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 440)];
        _headerView.backgroundColor = [UIColor whiteColor];
        _headerView.userInteractionEnabled = YES;
    }
    return _headerView;
}

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = [UIColor yc_colorWithUInt:0xf8f8f8];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableHeaderView = self.headerView;
    }
    return _tableView;
}

- (YCPlaceholderTextView *)textView
{
    if (!_textView) {
        _textView = [[YCPlaceholderTextView alloc] init];
        _textView.delegate = self;
        _textView.font = [UIFont systemFontOfSize:14];
        _textView.textColor = [UIColor yc_colorWithUInt:0x333333];
        _textView.placeholder = @"这一刻的想法...";
        _textView.placeholderColor = [UIColor yc_colorWithUInt:0x808080];
        _textView.inputAccessoryView = _inputAccessoryView;
        _textView.returnKeyType = UIReturnKeySend;
    }
    return _textView;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 10;
        layout.itemSize = CGSizeMake(80, 80);
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[YCImageCollectionViewCell class] forCellWithReuseIdentifier:@"imageCollectionViewCell"];
    }
    return _collectionView;
}


// 键盘辅助视图
-(UIToolbar *)inputAccessoryView
{
    if(!_inputAccessoryView)
    {
        UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
        UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(barButtonItemDidSelectAction:)];
        toolBar.items = @[[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],right];
        return toolBar;
    }
    return _inputAccessoryView;
}

- (NSMutableArray *)photoMutableArray
{
    if (!_photoMutableArray)
    {
        _photoMutableArray = [[NSMutableArray alloc] init];
    }
    return _photoMutableArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"发表日志";
    [self yc_addLeftBarButtonItemWithTitle:@"取消" target:self action:@selector(cancelBtnClick:)];
    [self yc_addRightDoneBarButtonItemWithTitle:@"发送" target:self action:@selector(sendBtnClick:)];
    [self makeView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

- (void)makeView
{
    [self.view addSubview:self.tableView];
    
    [self.headerView addSubview:self.textView];
    [self.headerView addSubview:self.collectionView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.right.equalTo(self.view);
    }];

    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@15);
        make.height.equalTo(@120);
        make.width.equalTo(@(kScreenWidth-30));
        make.top.equalTo(@20);
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.textView.mas_bottom).offset(20);
        make.left.equalTo(self.textView);
        make.width.height.equalTo(@260);
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.photoMutableArray.count >= 9)
    {
        return self.photoMutableArray.count;
    }
    else
    {
        return self.photoMutableArray.count+1;
    }
}

#pragma mark - UICollectionView delegate

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YCImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imageCollectionViewCell" forIndexPath:indexPath];
    
    if (indexPath.row == [self.photoMutableArray count] && [self.photoMutableArray count] != 9)
    {
        [cell.imageView setImage:[UIImage imageNamed:@"添加照片"]];
    }
    else
    {
//        GOImageModel *model = self.photoMutableArray[indexPath.row];
//        
//        if(model.localImage)
//        {
//            [cell.imageView setImage:model.localImage];
//        }
//        else
//        {
//            [cell.imageView yc_setWebImageWithURLString:model.imageURLString holderSize:CGSizeMake(80, 80)];
//        }
        UIImage *image = self.photoMutableArray[indexPath.item];
        cell.imageView.image = image;
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //可选图片数量
    self.numPhoto = 9 - self.photoMutableArray.count;
    [self.view endEditing:YES];
    
    if (self.photoMutableArray.count > 0 && indexPath.row < [self.photoMutableArray count])
    {
        NSMutableArray *images = [[NSMutableArray alloc] init];
        [self.photoMutableArray enumerateObjectsUsingBlock:^(UIImage *obj, NSUInteger idx, BOOL *stop) {
            
//            GOImageModel *model = obj;
//            if (model.localImage)
//            {
//                [images addObject:model.localImage];
//            }
//            else
//            {
//                [images addObject:model.imageURLString];
//            }
            [images addObject:obj];
        }];
        
        PreviewPhotoViewController *previewVC = [[PreviewPhotoViewController alloc] initWithImages:images displayIndex:indexPath.row rightBarButtonItemImageName:@"PreviewPhotoDelete" clickBlock:^(PreviewPhotoViewController *viewController, NSMutableArray *images, NSUInteger currentIndex) {
            
            [images removeObjectAtIndex:currentIndex];
            [self.photoMutableArray removeObjectAtIndex:currentIndex];
            [self.collectionView reloadData];
            
            if(images.count < 1)
            {
                [viewController.navigationController popToViewController:self.navigationController.childViewControllers[0] animated:YES];
            }
            else
            {
                NSInteger index = currentIndex - 1;
                if(index < 0)
                {
                    index = currentIndex + 1;
                }
                [viewController reloadWithImages:images displayIndex:index];
            }
        }];
        [self.navigationController pushViewController:previewVC animated:YES];
    }
    else
    {
        LXActionSheet *sheet = [[LXActionSheet alloc] initWithCancelButtonTitle:@"取消" otherButtonTitlesArray:@[@"从手机相册选择",@"拍照"]];
        [sheet showInView:self.navigationController.view mask:YES click:^(NSUInteger index, LXActionSheet *sheet) {
            
            switch (index) {
                case 1:
                {
                    YCLog(@"从手机相册中选择...");
                    
                    [MultipleImagePickerViewController presentMutipleImagePickerControllerAtViewController:self maxNumberOfImages:_numPhoto completion:^(NSArray *images) {
                        
                        for (NSDictionary *obj in images)
                        {
                            UIImage *image = obj[MutipleOriginImageKey];
                            
//                            GOImageModel *model = [[GOImageModel alloc]init];
//                            model.localImage = image;
                            [self.photoMutableArray addObject:image];
                        }
                        
                        [self.collectionView reloadData];
                        
                    } cancel:^{
                        
                    }];
                }
                    break;
                case 2:
                {
                    YCLog(@"拍照...");
                    
                    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
                    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                    imagePicker.delegate = self;
                    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                    [self presentViewController:imagePicker animated:YES completion:nil];
                    
                }
                    break;
                    
                default:
                    break;
            }
        } cancel:^(NSUInteger index, LXActionSheet *sheet){
            
        }];
    }
}

#pragma mark -tableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;//self.itemArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    if(!image)
    {
        [picker dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    
//    GOImageModel *model = [[GOImageModel alloc]init];
//    model.localImage = image;
//    [self.photoMutableArray addObject:model];
    [self.photoMutableArray addObject:image];
    [self.collectionView reloadData];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        [self sendBtnClick:nil];//发送
        return NO;
    }
    return YES;
}


- (void)textViewDidEndEditing:(UITextView *)textView
{
    
    [textView resignFirstResponder];
    
}

#pragma mark - 返回

// 导航条取消
- (void)cancelBtnClick:(UIBarButtonItem *)cancelItem
{
    YCLogFunc
    [self.navigationController popToViewController:self.navigationController.viewControllers[0] animated:YES];
}
// 发送
- (void)sendBtnClick:(UIBarButtonItem *)sendItem
{
    YCLogFunc
}

// 键盘辅助 确定
- (void)barButtonItemDidSelectAction:(UIBarButtonItem *)sender
{
    [self.view endEditing:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


@end
